import { Component, OnInit, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import { FormControl } from '@angular/forms/src/model';

@Component({
  selector: 'app-image-list-select',
  templateUrl: './image-list-select.component.html',
  styleUrls: ['./image-list-select.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR, // 注册令牌,说明这个是ng表单控件
      // 使用已有的数据 forwardRef 向前引用
      useExisting: forwardRef(() => ImageListSelectComponent),
      multi: true
    },
    {
      provide: NG_VALIDATORS, // 注册验证器
      // 使用已有的数据 forwardRef 向前引用
      useExisting: forwardRef(() => ImageListSelectComponent),
      multi: true
    },
  ]
})
// 继承 ControlValueAccessor 变成可以使用ngModel formControlName等属性的表单控件
export class ImageListSelectComponent implements ControlValueAccessor {
  @Input() cols = 6;
  @Input() rowHeight = '64px';
  @Input() title = '选择图片';
  @Input() items: string[] = [];
  @Input() useSvgIcon = false;
  @Input() itemWidth = '80px';
  selected: string;
  constructor() { }
  private propagateChnage = (_: any) => { };
  onChange(index: number) {
    this.selected = this.items[index];
    // 将值的变化通知表单
    this.propagateChnage(this.selected);
  }

  // 用于写入值
  writeValue(obj: any): void {
    // throw new Error("Method not implemented.");
    this.selected = obj;
  }
  // 注册监听表单值改变的事件
  registerOnChange(fn: any): void {
    // throw new Error("Method not implemented.");
    this.propagateChnage = fn;
  }

  // 注册onTouched状态事件
  registerOnTouched(fn: any): void {
    // throw new Error("Method not implemented.");
  }
  setDisabledState?(isDisabled: boolean): void {
    // throw new Error("Method not implemented.");
  }
  validate(c: FormControl): { [key: string]: any } {
    return this.selected ? null : {
      imageListInvalid: {
        valid: false
      }
    };
  }
}
